package com.eco.fanliapp.job.mtOrderJob;

import com.eco.fanliapp.common.constant.MeiTuanConfig;
import com.eco.fanliapp.entity.MtOrderDetail;
import com.eco.fanliapp.service.IMtOrderDetailService;
import com.eco.fanliapp.utils.HttpUtils;
import com.eco.fanliapp.utils.JsonUtils;
import com.eco.fanliapp.utils.MeiTuanAEC;
import com.eco.fanliapp.vo.respone.MeiTuanResponse;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @date 2020-03-09
 * 美团订单拉取
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
@Slf4j
public class MeiTuanOrderTask implements Job, Serializable {
    @Autowired
    private IMtOrderDetailService iMtOrderDetailService;
    @Override
    public void execute(JobExecutionContext context) {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();
        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行美团订单批量处理定时扫描任务-MeiTuanOrderTask：executeCount=" + executeCount + "--startTime=" + startTime);
        Integer page = 1;
        Integer size = 100;
        boolean  mt_order = true;
        StringBuilder url = new StringBuilder(MeiTuanConfig.ORDER_URL);
        String timestamp = String.valueOf(System.currentTimeMillis()/1000);
        Long time = Long.valueOf(timestamp);
        StringBuilder requestId = new StringBuilder(MeiTuanConfig.UTM_SOURCE_ID).append(timestamp);
        String access_token = MeiTuanAEC.encryptHex(requestId.toString(),MeiTuanConfig.PASS_KEY);
        Date now=new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String timeDate=dateFormat.format(now);
        url = url.append("?utmSource=").append(MeiTuanConfig.UTM_SOURCE_ID)//渠道ID
                .append("&accessToken=").append(access_token)//加密
                .append("&timestamp=").append(time)//时间戳
                .append("&requestId=").append(requestId.toString())//拼接生成
                .append("&version=").append(MeiTuanConfig.VERSEION)//版本
                .append("&startModifyDate=").append(timeDate)//时间
                .append("&endModifyDate=").append(timeDate)
                .append("&page=").append(page)//页数
                .append("&size=").append(size);//条数;//时间
        try {
            while (mt_order){
                String meiTuanRes = HttpUtils.sendGet(url.toString(), "");
                MeiTuanResponse meiTuanResponse = JsonUtils.getJsonToBean(meiTuanRes,MeiTuanResponse.class);
                if(meiTuanResponse.getCode() == 200){
                    MeiTuanResponse.PageModel pageModel= meiTuanResponse.getMsg();
                    log.info("******"+page.toString()+"******");
                    if(Integer.valueOf(pageModel.getRecordCount())/100 >= page-1){
                        List<MtOrderDetail> list = pageModel.getRecords();
                        if(list != null && list.size() > 0){
                            log.info(list.toString());
                            iMtOrderDetailService.saveOrUpdateBatch(list);
                        }
                        page++;
                    }else {
                        mt_order = false;
                    }
                }else {
                    mt_order = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行美团订单任务错误");
        }

        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行美团订单批量处理定时扫描任务-MeiTuanOrderTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }

}
